package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MenuServiceImpl (TODO)
 *
 * @author 许家磊
 * @version 1.0.0
 * @date 2019/8/7 18:46
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    /**
     * 通过用户名，获取该用户所能使用的菜单列表
     *
     * @param username -登录用户名
     * @return List<Map>
     */
    @Override
    public List<Map<String, Object>> getMenuListByUsername(String username) {
        //1.获取菜单列表集合
        List<Menu> mList = menuDao.getMenuListByUsername(username);
        //2.确定层级关系放入Map集合中
        /**
         * map格式
         * "path": "1",
         * "title": "工作台",
         * "icon": "fa-dashboard",
         * "linkUrl": "member.html",
         * "children": []
         * */
        //递归存放数据
        List<Map<String, Object>> lmap = listRecursion(mList);
//        Menu menu = new Menu();
//        menu.setPath("1");
//        menu.setLevel();
        Map<String, Object> map = new HashMap<>();
        map.put("path", "1");
        map.put("title", "工作台");
        map.put("icon", "fa-dashboard");
        map.put("children", new ArrayList<>());
        lmap.add(0,map);
        //System.out.println(mList);
        //3.返回
        return lmap;
    }

    /**
     * 递归分层
     * @param mList -原始集合
     * @return List<Map<String, Object>>
     */
    private List<Map<String, Object>> listRecursion(List<Menu> mList) {
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        /**
         * map格式
         * "path": "1",
         * "title": "工作台",
         * "icon": "fa-dashboard",
         * "linkUrl": "member.html",
         * "children": []
         * */
        mList.forEach(menu -> {
            List<Menu> subMList = menu.getChildren();
            Map<String, Object> map = new HashMap<>();
            map.put("path", menu.getPath());
            map.put("title", menu.getName());
            map.put("icon", menu.getIcon());
            map.put("linkUrl", menu.getLinkUrl());
            map.put("children", listRecursion(subMList));
            maps.add(map);
        });
        return maps;
    }
}
